//
//  DataBaseEngine.m
//  CarCare
//
//  Created by ileo on 15/3/26.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "DataBaseEngine.h"
#import "AIUserInfo.h"
#import "FMResultSet+FMDBHelpers.h"
#import "CacheMgr.h"
#import <sqlite3.h>

@implementation DataBaseEngine

-(instancetype)init{
    self = [super init];
    if (self) {
        [self reOpenDataBase];
    }
    return self;
}

-(void)createTable{}

-(void)reOpenDataBase{
    if (self.dataBase) {
        self.dataBase = nil;
    }
    NSString *path = [NSString stringWithFormat:@"carcare_%zd.db",USERINFO.userID];
    self.dataBase = [FMDatabase databaseWithPath:[CacheMgr nonTmpCachePathWithName:path]];
    [self createTable];
}

-(void)reCreateTable{
    [self dropTable];
    [self createTable];
}

-(void)dropTable{
    [self.dataBase open];
    if ([self.dataBase tableExists:self.tableName]) {
        NSError *error = nil;
        if ([self.dataBase dropTableIfExistsWithName:self.tableName error:&error]) {
        }
    }
    [self.dataBase close];
}

-(NSArray *)datas{
    [self.dataBase open];
    NSError *error = nil;
    NSArray *datas = nil;
    
    datas = [self.dataBase selectResults:nil
                                    from:self.tableName
                                   where:self.where
                                 groupBy:nil
                                  having:nil
                               arguments:self.arguments
                                 orderBy:self.orderBy
                                   limit:(self.limit == 0 ? nil : @(self.limit))
                                  offset:(self.offset == 0 ? nil : @(self.offset))
                                   error:&error].allRecords;
    
    [self.dataBase close];
    
    if (error) {
        return nil;
    }
    return datas;
}
-(void)addDatas:(NSArray *)datas{
    [self.dataBase open];
    NSArray *coleumns = [[datas firstObject] allKeys];
    
    NSError *error = nil;
    NSMutableArray *needEdit = [NSMutableArray arrayWithCapacity:datas.count];
    NSInteger success = 0;
    NSInteger fail = 0;
    for (NSDictionary *dic in datas) {
        if([self.dataBase insertInto:self.tableName columns:coleumns values:@[[dic allValues]] error:&error]){
            success++;
        }
        if (error) {
            if (error.code == SQLITE_CONSTRAINT) {
                [needEdit addObject:dic];
            }else{
                fail++;
            }
        }
    }
    
    NSLog(@"** %@ add ** count : %zd success : %zd  fail : %zd exist : %zd",self.tableName,datas.count,success,fail,needEdit.count);
    
    [self.dataBase close];
    
    [self editDatas:needEdit];
}

-(void)removeDatas:(NSArray *)datas{
    [self.dataBase open];
    NSMutableString *where = [NSMutableString stringWithFormat:@"%@",self.where];
    
    [where appendFormat:@" IN("];
    for (NSDictionary *dic in datas) {
        [where appendFormat:@"%@,",dic[self.where]];
    }
    NSRange range = NSMakeRange(where.length - 1, 1);
    [where deleteCharactersInRange:range];
    [where appendFormat:@")"];
    
    NSError *error = nil;
    if([self.dataBase deleteFrom:self.tableName where:where arguments:nil error:&error]){
        NSLog(@"%@ delete ok",self.tableName);
    }
    if (error) {
        NSLog(@"%@ delete fail : %@",self.tableName,error);
    }
    [self.dataBase close];
}

-(void)editDatas:(NSArray *)datas{
    [self.dataBase open];
    NSInteger success = 0;
    NSInteger fail = 0;
    for (NSDictionary *dic in datas) {
        NSString *where = [NSString stringWithFormat:@"%@ = '%@'",self.where,dic[self.where]];
        NSError *error = nil;
        if([self.dataBase update:self.tableName values:dic where:where arguments:nil error:&error] > 0){
            success++;
        }
        if (error) {
            fail++;
        }
    }
    NSLog(@"** %@ edit ** count : %zd success : %zd  fail : %zd",self.tableName,datas.count,success,fail);
    [self.dataBase close];
}

@end